import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute, Router } from '@angular/router';
import { forkJoin } from 'rxjs';
import { DatePipe } from '@angular/common';

import { PurchaseOrderAddService } from './purchase-order-add.service';
@Component({
    selector: 'app-purchase-order-add',
    templateUrl: './purchase-order-add.component.html',
    styleUrls: ['./purchase-order-add.component.scss'],
    providers: [DatePipe]
})
export class PurchaseOrderAddComponent implements OnInit {

    // 传递参数
    routeParams: any = {};
    formDatas: any = {
        examineLoading: false,
        draftLoading: false,
        purchaseNumber: '', // 采购单号
        purchase: {
            applyNumber: '', // 采购申请单
            applyNumberId: '', // 计划单ID
            state: '', // 状态(0 草稿 1待审核 2审核通过 3审核不通过 4入库中 5已完成 6已关闭)
            partyB: '', // 供应商(乙方)
            remark: '', // 备注
            firstParty: '48' // 甲方 需求改动 甲方暂时爱达普科技有限公司
        },
        list: [],
        countTotal: '', // 采购总数
        deliveryTime: '' // 批量日期
    };
    // 计划单下拉list
    planSheetLists: any = [];
    // 供应商下拉list
    supplierLists: any = [];

    // 表格行宽arry
    nzWidthConfig: string[] = ['50px','100px','250px','200px','150px','150px','150px','150px','150px','150px','200px','150px','150px','100px','120px'];
    planTableLoading: boolean = false;
    // 计划单table
    planSheetTables: any = [];
    // 已选table
    selectedTables: any = [];
    // 详情已选table
    backupSelectedTables: any = [];

    constructor(
        private ref: ChangeDetectorRef,
        private router: Router,
        private datePipe: DatePipe,
        private activatedRoute: ActivatedRoute,
        private message: NzMessageService,
        private purchaseOrderAddService: PurchaseOrderAddService
    ) {
        this.activatedRoute.params.subscribe((res: any) => {
            this.routeParams = res;
        })
    }
    ngOnInit() {
        let postArr: any = [this.purchaseOrderAddService.getPlanList(), this.purchaseOrderAddService.getSupplierList()];
        forkJoin(postArr).subscribe((list: any) => {
            let planList = list[0];
            let supplierList = list[1];

            // 计划下拉list
            if (planList.code == 0 && planList.data.records && planList.data.records.length) {
                this.planSheetLists = planList.data.records.filter((item: any) => { return item.state == 2 || item.state == 4; })
            }

            // 供应商下拉list
            if (supplierList.code == 0 && supplierList.data.records && supplierList.data.records.length) {
                this.supplierLists = supplierList.data.records.filter((item: any) => { return item.state == 1; })
            }

            // 编辑跳转
            if (this.routeParams.id != 0) {
                this.getDetailsData();
            }

            // 生成采购单跳转
            if (this.routeParams.type && this.routeParams.type == 'create') {
                this.formDatas.purchase.applyNumber = this.routeParams.number;

                let jhdId = this.planSheetLists.filter((item: any) => { return item.billNo == this.routeParams.number })[0].id;
                this.getPlanTableData(jhdId);
            }
        })
    }

    // 查询详情
    getDetailsData() {
        this.purchaseOrderAddService.details(this.routeParams.id).subscribe((res: any) => {
            if (res.code == 0) {
                const { list, purchase }: any = res.data;
                this.formDatas.purchaseNumber = purchase.purchaseNumber;

                this.formDatas.purchase.applyNumber = purchase.applyNumber; // 计划单号
                this.formDatas.purchase.state = purchase.state; // 状态
                this.formDatas.purchase.applyNumberId = purchase.applyNumberId; // 计划单号ID
                this.formDatas.purchase.partyB = purchase.partyB ? Number(purchase.partyB) : ''; // 供应商(乙方)
                this.formDatas.purchase.remark = purchase.remark; // 备注
                // 用作判断编辑时当前项是否可点击
                this.backupSelectedTables = list.map((item: any) => { return item.planId });

                list.map((item: any) => item.isShow = 1);
                this.selectedTables = list;

                // 获取计划单table
                this.planSheepChange(purchase.applyNumber, 'init');
            }
        }, (error: any) => {
            this.message.error(error || '获取详情失败');
        })
    }

    // 查询计划单table
    getPlanTableData(id: any) {
        this.planTableLoading = true;
        this.purchaseOrderAddService.getPlanDetails(id).subscribe((res: any) => {
            this.planTableLoading = false;
            if (res.code == 0 && res.data.list && res.data.list.length) {
                this.planSheetTables = res.data.list.map((item: any) => {
                    let obj: any = {};
                    if (item.state != -1) {
                        obj = {
                            ...item,
                            planId: item.id,
                            isShow: 0 // 用作操作采购 && 取消采购
                        }
                    }
                    return obj
                })

                if (this.routeParams.id) {
                    let tempList = this.selectedTables.map((tag: any) => {
                        return tag.planId;
                    })
                    this.planSheetTables.forEach((ele: any) => {
                        if (tempList.includes(ele.planId)) {
                            ele.isShow = 1;
                        }
                    });
                }

                this.formDatas.purchase.applyNumberId = res?.data?.procurementPlan?.id;
            }
        }, (error: any) => {
            this.planTableLoading = false;
            this.planSheetTables = [];
        })
    }

    // 计划单change
    planSheepChange(billNo: any, init?: string) {
        if (!init) {
            this.selectAll(1);
        }

        let selectedId = this.planSheetLists.filter((item: any) => { return item.billNo == billNo })[0].id;
        
        this.getPlanTableData(selectedId);
    }

    /**
     * 保存
     * @param state 0 草稿 1待审核 2审核通过 3审核不通过 4入库中 5已完成 6已关闭
     */
    preserData(state: number) {
        if (!this.verifData()) {
            return
        }
        let params = {
            purchase: this.formDatas.purchase,
            list: JSON.parse(JSON.stringify(this.selectedTables))
        }
        params.purchase.state = state;
        params.list.forEach((ele: any) => {
            ele.deliveryTime = this.datePipe.transform(ele.deliveryTime, 'yyyy-MM-dd');

            // 清除冻结数量防止后端入库出现bug
            ele.frozenNumber = '';
            ele.planFrozenNumber = '';

            if (this.routeParams.id == '0') {
                delete ele.id;
            }
        });

        if (this.routeParams.id == '0') {
            // 新增
            this.formDatas.examineLoading = true;
            this.purchaseOrderAddService.save(params).subscribe((res: any) => {
                this.formDatas.examineLoading = false;
                if (res.code == 0) {
                    this.message.success('保存成功');
                    this.router.navigate(['stock/purchaseOrder']);
                } else {
                    this.message.error(res.message || '保存失败');
                }
            }, (error: any) => {
                this.formDatas.examineLoading = false;
                this.message.error(error || '保存失败');
            });
        } else {
            // 编辑修改
            params.purchase.id = this.routeParams.id;

            this.formDatas.draftLoading = true;
            this.purchaseOrderAddService.update(params).subscribe((res: any) => {
                this.formDatas.draftLoading = false;
                if (res.code == 0) {
                    this.message.success('保存成功');
                    this.router.navigate(['stock/purchaseOrder']);
                } else {
                    this.message.error(res.message || '保存失败');
                }
            }, (error: any) => {
                this.formDatas.draftLoading = false;
                this.message.error(error || '保存失败');
            });
        }
    }

    /**
     * 全部采购 & 清空全部
     * @param num 
     */
    selectAll(num: number) {
        if (num == 0) {
            let isAdd = this.planSheetTables.every((item: any) => {
                return item.isShow == 1;
            })
            if (isAdd) {
                this.message.warning('当前无可添加项');
                return
            }

            this.planSheetTables.forEach((ele: any, index: number) => {
                if (ele.isShow == 0 && (ele.maxPurchasedNumber > 0 || this.backupSelectedTables.includes(ele.planId))) {
                    this.singleChoice(ele, index)
                }
            });

            this.setCountTotal();
        } else {
            this.selectedTables = [];
            this.planSheetTables.map((item: any) => item.isShow = 0);
        }
    }
    /**
     * 单个采购 || 取消
     * @param item 
     * @param index 
     */
    singleChoice(item: any, index: number) {
        // isShow 0：可添加状态，1：移除状态
        switch (item.isShow) {
            case 0:
                this.planSheetTables[index].isShow = 1;
                this.selectedTables.push({...item, isShow: 1, purchaseNumber: item.maxPurchasedNumber});
                break;
            case 1:
                let topDeleteIndex = this.planSheetTables.findIndex((ele: any) => ele.planId == item.planId);
                let bomDeleteIndex = this.selectedTables.findIndex((ele: any) => ele.planId == item.planId);
                
                this.planSheetTables[topDeleteIndex].isShow = 0;
                this.selectedTables.splice(bomDeleteIndex, 1);
                break;
        }
        this.setCountTotal();
    }

    // onKeydownEnter
    onKeydownEnter(ev: any, index: number) {
        const { keyCode } = ev
        if (keyCode == 13) {
            document.getElementById(`orderAddID${index + 1}`)?.focus();
        }
    }
    // onKeydownPriceEnter
    onKeydownPriceEnter(ev: any, index: number) {
        const { keyCode } = ev
        if (keyCode == 13) {
            document.getElementById(`orderPriceID${index + 1}`)?.focus();
        }
    }
    // 采购数量输入框失去焦点
    onBlurCountNum() {
        this.setCountTotal();
    }

    // 出库数量累加
    setCountTotal() {
        this.formDatas.countTotal = this.selectedTables.reduce((total: any, item: any) => {
            return total + item.purchaseNumber
        }, 0);
    }
    // 批量修改日期
    onTableChangeTime(ev: any, key: string) {
        this.selectedTables?.forEach((element: any) => {
            element[key] = ev
        });
    }
    // 验证
    verifData() {
        if (!this.formDatas.purchase.applyNumber) {
            this.message.warning("请选择计划申请单");
            return false;
        }
        if (!this.formDatas.purchase.partyB) {
            this.message.warning("请选择供应商");
            return false;
        }
        if (!this.selectedTables.length) {
            this.message.warning("请选择采购内容");
            return false;
        }
        
        for (let i = 0; i < this.selectedTables.length; i++) {
            const { deliveryTime, purchasePrice, maxPurchasedNumber, purchaseNumber } = this.selectedTables[i];
            if (!deliveryTime) {
                this.message.warning("交货日期不能为空");
                return;
            }
            if (!purchaseNumber) {
                this.message.warning("采购数量不能为空");
                return;
            }
            if (!purchasePrice) {
                this.message.warning("采购单价不能为空");
                return;
            }
            if (purchaseNumber > maxPurchasedNumber) {
                this.message.warning("采购数量已经超过最大采购数量, 请从新输入采购数量");
                return;
            }
        }
        return true;
    }
    // 文字转换
    state_to_text(s: any) {
        let test = "";
        switch (s) {
            case 0:
                test = "采购";
                break;
            case 1:
                test = "已手动关闭";
                break;
            case 2:
                test = "已完成采购";
                break;
            case 3:
                test = "入库";
                break;
            default:
                test = "-";
                break;
        }
        return test;
    }
}
